import React, { useState } from 'react';
import { ProFormCascader } from '@ant-design/pro-components';
import { convertValue, getSelectList, transformValue } from '@/util/util';
import { getDistrict } from '@/services/micro/district';

type MyProTableProps = {
  name?: string;
  required?: boolean;
};

interface Option {
  value?: string;
  label: React.ReactNode;
  children?: Option[];
  isLeaf?: boolean;
  loading?: boolean;
}

const MyAddressCascader: React.FC<MyProTableProps> = ({ name = 'address', required = true }) => {
  const [options, setOptions] = useState<Option[]>([]);

  const getData = async (parentId = '0') => {
    const ret = await getSelectList({
      label: 'title',
      value: 'id',
      server: () => getDistrict({ parentId }),
    });
    return (
      ret.map((c) => {
        return {
          ...c,
          isLeaf: false,
        } as Option;
      }) || []
    );
  };

  const loadData = (selectedOptions: Option[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    if (targetOption.children) return;
    getData(targetOption.value).then((ret) => {
      targetOption.children = ret;
      if (!ret.length) targetOption.isLeaf = true;
      setOptions([...options]);
    });
  };

  /**
   * 根据回调请求数据回显
   * @param {string[]} val
   * @param {Option[]} list
   * @param {number} i
   * @returns {Promise<Option[]>}
   */
  const getEchoData = async (val: string[], list: Option[], i = 0) => {
    for (const b of list) {
      if (b.value === val[i]) {
        const ret = await getData(b.value);
        b.children = await getEchoData(val, ret, i + 1);
        if (!ret.length) b.isLeaf = true;
        break;
      }
    }
    return list;
  };

  return (
    <ProFormCascader
      label="地址"
      name={name}
      convertValue={(value) => {
        //接收转化
        let newValue = value;
        if (value && typeof value === 'string') {
          newValue = convertValue(value);
          if (newValue.length && !options.length) {
            getData().then((ret) => {
              getEchoData(newValue, ret).then((list) => {
                setOptions(list);
              });
            });
          }
        }
        return newValue;
      }}
      transform={(value) => transformValue(value)}
      fieldProps={{
        options,
        loadData,
        changeOnSelect: true,
        onDropdownVisibleChange: (value) => {
          if (value && !options.length) {
            getData().then((ret) => {
              setOptions(ret);
            });
          }
        },
      }}
      rules={[
        {
          required: required,
          message: '地址为必填项',
        },
      ]}
    />
  );
};
export default MyAddressCascader;
